/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sgt.supermarket.hibernatedao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import sgt.supermarket.entity.Customer;

/**
 *
 * @author THUY TUNG
 */
public class HibernateCustomerDAO extends HibernateGenericDAO<Customer, Long> {

    public HibernateCustomerDAO(Session session) {
        super(session);
    }

    public List<Customer> getByKeyword(String keyword) {
        String likePhrase = "%" + keyword + "%";
        return getSession().createCriteria(Customer.class).add(
                Expression.or(
                Expression.ilike("personalId", likePhrase),
                Expression.or(
                Expression.ilike("name", likePhrase),
                Expression.ilike("cellphone", likePhrase)))).list();
    }

    public long getIdByUsernameAndPassword(String username, String password) {
        long id = 0;
        for (Customer c : this.getAll()) {
            if (c.getName().equals(username) && c.getPassword().equals(password)) {
                id = c.getAutoId();
            }
        }
        return id;
    }

    public Customer getByCellphone(String cellphone) {
        return (Customer) getSession().createCriteria(Customer.class).add(Expression.eq("cellphone", cellphone)).uniqueResult();
    }

    public Customer getByPersonalId(String personalId) {
        return (Customer) getSession().createCriteria(Customer.class).add(Expression.eq("personalId", personalId)).uniqueResult();
    }

    public Customer getByPersonalIdOrCellphone(String personalId, String cellphone) {
        List<Customer> customers = getSession().createCriteria(Customer.class).add(
                Expression.or(
                Expression.eq("cellphone", cellphone),
                Expression.eq("personalId", personalId))).list();
        if (customers.size() >= 1) {
            return customers.get(0);
        } else {
            return null;
        }
    }
}
